import * as dayjs from 'dayjs'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 后端时间转换成 YYYY-mm-dd HH:mm:ss
 * @param {String} dateStr 时间字符串
 */
export function formatterTime(dateStr) {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

/**
 * 两位小数,四舍五入,不补0
 * @param {*} num
 * @param {*} limitLenght 限制小数位
 */
export function toDecimalNoZero(num, limitLenght = 2) {
  let f = parseFloat(num)
  if (isNaN(f)) {
    return false
  }

  // 拼接 2位数小数100 3位小数:1000 3位小数10000
  let resultLength = '1'
  for (let i = 0; i < limitLenght; i++) {
    resultLength += '0'
  }

  f = Math.round(num * Number(resultLength)) / Number(resultLength)
  const s = f.toString()
  return s
}

/**
 * 每3位加上逗号
 * @param {*} num
 */
export function toThousands(val) {
  const str = (val || 0).toString()
  return (str).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
}

/**
 * base64图片转file
 * @param {*} dataurl Base 64文件
 * @param {*} filename 文件名称
 * @returns File()
 */
export function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
/**
 * url转file类型
 * @param {*} img url
 * @returns File()
 */
export function fileProcess(img) {
  const fileName = img.split('/').pop()
  const type = fileName.split('.').pop()
  return new Promise((resolve, reject) => {
    dataURLtoBlob(img, function(blobData) {
      var file = new File([blobData], fileName, { type: 'image/' + type })
      resolve(file)
    })
  })
}
/**
 * 图片url格式转为blob格式
 * @param {*} fileUrl url
 * @param {*} filename 文件名称
 * @param {*} _this 作用域
 * @returns File()
 */
export async function dataURLtoBlob(dataurl, callback) {
  const xhr = new XMLHttpRequest()
  xhr.open('get', dataurl, true)
  xhr.responseType = 'blob'
  xhr.onload = function(res) {
    if (this.status === 200) {
      var blob = this.response
      callback(blob)
    }
  }
  await xhr.send()
}
/**
 * 将url转换为base64
 * @param {*} img
 * @returns File()
 */
export function getBase64Image(img) {
  var demoCanvas = document.createElement('canvas')
  demoCanvas.width = img.width
  demoCanvas.height = img.height
  var ctx = demoCanvas.getContext('2d')
  ctx.drawImage(img, 0, 0, 300, 150)
  var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
  var dataURL = demoCanvas.toDataURL('image/' + ext)
  return {
    dataURL: dataURL,
    type: 'image/' + ext
  }
}

/**
 * 把 https:// 或者 http:// 去掉，返回主要内容
 * @param {*} dataurl Base 64文件
 * @param {*} filename 文件名称
 * @returns File()
 */
export function deleteHttp(url) {
  return url.split('//')[1]
}

/**
 * 初始化 el-dialog 数据
 * @param {*} formRef el-form ref
 * @param {*} ruleValidate el-form 校验规则
 * @param {*} that 作用域
 * @returns File()
 */
export function dialogDataRest(formRef, ruleValidate, that, ...excludeFields) {
  // 初始化数据
  that.$refs[formRef].resetFields()
  const obj1 = that.$data
  const obj2 = that.$options.data.call(that)
  if (!excludeFields || excludeFields.length === 0) {
    excludeFields = [ruleValidate]
  }
  for (const attrName in obj1) {
    if (excludeFields && excludeFields.includes(attrName)) {
      continue
    }
    obj1[attrName] = obj2[attrName]
  }
}

/**
 * 获取后缀名
 * @param {*} filename
 * @returns fileType
 */
export function extname(filename) {
  if (!filename || typeof filename !== 'string') {
    return false
  }
  const a = filename.split('').reverse().join('')
  const b = a.substring(0, a.search(/\./)).split('').reverse().join('')
  return b
}

/**
 * 下划线命名转驼峰命名
 * @param {str} name_yxj_com
 * @returns nameYxjCom
 */
export function toChangeCase(str) {
  // 匹配一个或多个下划线+ 后一个不是以下划线开头的字符
  let nstr = str.replace(/(?:_)+([^_])/g, function($0, $1) {
    return $1.toUpperCase()
  })
  nstr = nstr.replace(nstr[0], nstr[0].toLowerCase())
  return nstr
}

/**
 * 判断是否含有大写字母
 * @param {str} string
 * @returns boolean
 */
export function hasCapital(str) {
  var result = str.match(/^.*[A-Z]+.*$/)
  if (result == null) return false
  return true
}

/**
 * 判断是否含有小写字母
 * @param {str} string
 * @returns boolean
 */
export function hasLowercase(str) {
  var result = str.match(/^.*[a-z]+.*$/)
  if (result == null) return false
  return true
}

/**
 * 把对象的Key值，从下划线转换成驼峰
 * @param {obj} Object
 * @returns obj
 */
export function toObjectChangeCase(obj) {
  // {
  //   key_one: 'abc' => keyOne: 'abc'
  // }
  for (const key in obj) {
    const newKey = toChangeCase(key)
    obj[newKey] = obj[key]
    if (hasCapital(newKey) === true) {
      delete obj[key]
    }
  }
  return obj
}
